package com.hhxy.handler.exception;

import com.hhxy.constants.SystemConstants;
import com.hhxy.utils.response.AppHttpCodeEnum;
import com.hhxy.utils.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @author ghp
 * @date 2023/4/17
 * @title 全局异常处理器
 * @description 用于捕获Controller层中抛出的异常
 */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(CustomException.class)
    public ResponseResult<String> exceptionHandler(CustomException e) {
        log.error("系统抛出了异常，异常信息:{}", e.getMessage());
        return ResponseResult.errorResult(SystemConstants.EXCEPTION_CODE, e.getMessage());
    }

    /**
     * 捕获唯一性约束异常
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResponseResult<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.error("执行SQL时发生唯一性异常，异常信息:{}", e.getMessage());
        // 给出更加详细的提示信息
        if (e.getMessage().contains("Duplicate entry")) {
            // 截取出重复的name，然后给出提示信息
            String msg = e.getMessage();
            int index = msg.indexOf("Duplicate entry");
            msg = msg.substring(index);
            String[] split = msg.split(" ");
            msg = split[2] + "已存在";
            return ResponseResult.errorResult(SystemConstants.EXCEPTION_CODE, msg);
        }
        // 其它异常
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
    }

    /**
     * 捕获参数校验异常
     * 备注：@RequestBody上@validate失败后抛出的异常是MethodArgumentNotValidException异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult exceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数校验出错，异常信息:{}", e.getMessage());
        // 方式一：
//        BindingResult bindingResult = e.getBindingResult();
//        StringBuilder message = new StringBuilder();
//        if (bindingResult.hasErrors()) {
//            List<ObjectError> allErrors = bindingResult.getAllErrors();
//            for (ObjectError allError : allErrors) {
//                message.append(allError.getDefaultMessage()).append(", ");
//            }
//        }
        // 方式二：
        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining("，"));
        return ResponseResult.errorResult(SystemConstants.EXCEPTION_CODE, message.toString());
    }

    /**
     * 捕获参数校验异常
     * 备注：处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseResult BindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining("，"));
        return ResponseResult.errorResult(SystemConstants.EXCEPTION_CODE, message);
    }

    /**
     * 捕获参数校验异常
     * 备注：处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ResponseResult ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining("，"));
        return ResponseResult.errorResult(SystemConstants.EXCEPTION_CODE, message);
    }

}
